package com.loadburn.heron.render;

import com.google.common.collect.Maps;
import com.google.inject.Provider;

import java.io.Serializable;
import java.util.Map;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 14-1-11
 */
public class RedirectAttributesProvider implements Provider<RedirectAttributes>, Serializable {


    private static final long serialVersionUID = -4848922067440034042L;


    @Override
    public RedirectAttributes get() {
        final Map<String, Object> flashAttributes = Maps.newLinkedHashMap();

        return new RedirectAttributes() {
            @Override
            public Map<String, Object> asMap() {
                return flashAttributes;
            }

            @Override
            public RedirectAttributes addFlashAttribute(String attributeName, Object attributeValue) {
                flashAttributes.put(attributeName, attributeValue);
                return this;
            }

            @Override
            public RedirectAttributes addAllFlashAttribute(Map<String, ?> attributes) {
                if (attributes != null) {
                    flashAttributes.putAll(attributes);
                }
                return this;
            }

            @Override
            public Map<String, ?> getFlashAttributes() {
                return flashAttributes;
            }


            public RedirectAttributes addAttribute(String attributeName, Object attributeValue) {
                flashAttributes.put(attributeName, attributeValue);
                return this;
            }

            public RedirectAttributes addAllAttributes(Map<String, ?> attributes) {
                if (attributes != null) {
                    flashAttributes.putAll(attributes);
                }
                return this;
            }

            public RedirectAttributes mergeAttributes(Map<String, ?> attributes) {
                if (attributes != null) {
                    for (String key : attributes.keySet()) {
                        if (!flashAttributes.containsKey(key)) {
                            flashAttributes.put(key, attributes.get(key));
                        }
                    }
                }
                return this;
            }

            public boolean containsAttribute(String attributeName) {
                return flashAttributes.containsKey(attributeName);
            }
        };
    }
}
